<?php

namespace App\Repositories;

use App\Models\Orders;
use App\Models\User;
use BobCoder\Construct\Foundation\Repository\Repository;

class UserRepository extends Repository
{
    protected $model;

    public function __construct()
    {
        $this->model = new User();
    }


    /**
     * 会员分页
     * @param int $companyId 公司ID
     * @param int $pageSize
     * @param array $columns
     * @return mixed
     * @Author 姿势就是力量
     */
    public function getPageList(int $companyId, int $sex, int $pageSize = 10, array $columns = ['*'], string $nick_name = '', string $phone = '', string $name = '', string $date = '', string $balance = '', string $linkman = '', string $linkphone = '')
    {

        return $this->model->select($columns)
            ->with(['company:id,name'])
            ->when($nick_name, function ($query) use ($nick_name) {
                $query->where('nick_name', 'like', '%' . $nick_name . '%');   //昵称
            })
            ->when($phone, function ($query) use ($phone) {
                $query->where('phone', 'like', '%' . $phone . '%');    //手机号
            })
            ->when($sex, function ($query) use ($sex) {
                $query->where('sex', 'like', '%' . $sex . '%');      //性别
            })
            ->when($balance, function ($query) use ($balance) {
                $query->where('balance', 'like', '%' . $balance . '%');      //余额
            })
            ->when($linkman, function ($query) use ($linkman) {
                $query->where('linkman', 'like', '%' . $linkman . '%');      //紧急联系人
            })
            ->when($linkphone, function ($query) use ($linkphone) {
                $query->where('linkphone', 'like', '%' . $linkphone . '%');      //紧急联系人电话
            })
            ->when($name, function ($query) use ($name) {
                $query->whereHas('company', function ($query2) use ($name) {
                    $query2->where('name', 'like', '%' . $name . '%');   //公司名称
                });
            })
            ->when($date, function ($query) use ($date) {
                if ($date) {
                    $list = explode(',', $date);
                    $query->whereBetween('created_at', [$list[0], $list[1]]); //时间选择
                }
            })
            ->company($companyId)
            ->orderBy('created_at', 'desc')
            ->paginate($pageSize)
            ->toArray();

    }


    /**
     * 保存会员信息
     * @param array $data
     * @return User|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model
     * @Author 姿势就是力量
     */
    public function saveData(array $data)
    {
        if (!empty($data['id'])) {
            $model = $this->find($data['id']);
        } else {
            $model = $this->model;
        }

        foreach ($data as $key => $value) {
            $model->{$key} = $value;
        }
        $model->save();

        return $model;
    }

}
